import * as app from '../../common/utils/BaseApp'
import { deepClone } from '@/utils'
import * as ck from '../../common/utils/validater'
import * as utils from '@/utils/verify'
import { hasActionPriv } from '@/utils/perm'
import * as elg from '../../common/utils/ElmGenerator'
import { flatArrayToTree } from '../../common/utils/ComUtil'

import { queryOrgList, getOrgList, createOrg, updateOrg, deleteOrg } from '@/api/system/org'
import { getPersonInCharge } from '@/api/system/user'
import langFile from './org.lang'
const base = app.install({ langObj: langFile })
const pageMode = {
  add: 'add',
  detailAdd: 'detailAdd',
  update: 'update'
}
export default {
  mixins: [base],
  data() {
    return {
      formObj: {
        searchForm: {
          // ----------------------- 组织查询条件 ---------------------
          org: {
            orgName: '',
            orgType: ''
          },
          likeSearch: {
            org: ['orgName']
          }
        },
        addForm: {
          // ----------------------- 组织Form结构 ---------------------
          org: {
            id: undefined,
            parentId: [],
            orgId: '',
            orgName: '',
            sortOrder: '',
            personInCharge: '',
            memo: ''
          },
          showFlg: {
            org: false
          },
          showMode: {
            org: ''
          },
          orgTreeData: [],
          personInChargeData: []
        }
      },
      listObj: {
        // ----------------------- 组织列表 ---------------------
        org: {
          ...base.$gcom.getDefListObj()
        }
      }
    }
  },
  computed: {
    isAddOrg() {
      return this.formObj.addForm.showMode.org === pageMode.add ||
             this.formObj.addForm.showMode.org === pageMode.detailAdd
    },
    orgSearchFormLayout() {
      const formItems = [
        elg.createInput(this, { bindId: 'orgName', propsOpt: { width: 180 }}),
        hasActionPriv(['sys:org:query']) === false ? null
          : elg.createButton(this, this.handleSearchOrg, { langId: 'search', actionValid: true, propsOpt: { icon: 'el-icon-search' }}),
        elg.createBR(),
        hasActionPriv(['sys:org:add']) === false ? null
          : elg.createButton(this, this.handleAddOrg, { langId: 'add', propsOpt: { icon: 'el-icon-edit' }})
      ]
      const rules = {
        orgName: [ck.createMaxLenValidater(this, 150)]
      }
      return { formItems: formItems, rules: rules }
    },
    orgAddFormLayout() {
      const formItems = [
        elg.createSelectTree(this, { bindId: 'parentId', treeData: this.formObj.addForm.orgTreeData, propsOpt: { multiple: false }}),
        elg.createInput(this, { bindId: 'orgId' }),
        elg.createInput(this, { bindId: 'orgName' }),
        elg.createInputNumber(this, { bindId: 'sortOrder' }),
        elg.createSelect(this, { bindId: 'personInCharge', optionList: elg.createChildOption(this.formObj.addForm.personInChargeData),
          propsOpt: { width: 160, multiple: false, filterable: true, remote: true, 'remote-method': this.searchPersonInCharge }}),
        elg.createTextArea(this, { bindId: 'memo' })
      ]
      const footerItems = [
        hasActionPriv(['sys:org:add', 'sys:org:update']) === false ? null
          : elg.createButton(this, this.handleSaveOrg, { langId: 'confirm', actionValid: true, propsOpt: { icon: '' }})
      ]
      const rules = {
        orgId: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 20)
        ],
        parentId: [
          ck.createCustomValidater(this, this.parentIdRequiredValidator)
        ],
        orgName: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 150)
        ],
        sortOrder: [
          ck.createRequiredValidater(this)
        ],
        memo: [
          ck.createMaxLenValidater(this, 255)
        ]
      }
      return { formItems: formItems, footerItems: footerItems, rules: rules }
    },
    orgListLayout() {
      const itemColumns = [
        elg.createTableColumn(this, { bindId: 'orgName', align: 'left' }),
        elg.createTableColumn(this, { bindId: 'orgId', align: 'center' }),
        elg.createTableColumn(this, { bindId: 'personInCharge', align: 'center' }),
        elg.createTableColumn(this, { bindId: 'memo', align: 'center' })
      ]
      const actionColumns = [
        hasActionPriv(['sys:org:update']) === false ? null
          : elg.createTableAction(this, { langId: 'edit', actionFnc: this.handleUpdateOrg }),
        hasActionPriv(['sys:org:delete']) === false ? null
          : elg.createTableAction(this, { langId: 'delete', actionFnc: this.handleDeleteOrg })
      ]
      return { columns: itemColumns, actions: actionColumns }
    }
  },
  created() {
    this.$gcom.formObj = deepClone(this.formObj)
    this.searchOrgList()
  },
  methods: {
    handleSearchOrg() {
      this.validateAll(['searchForm'], () => {
        this.listObj.org.pagingDefine.page = 1
        this.searchOrgList()
      })
    },
    async handleAddOrg(row, index) {
      await this.setOrgTreeData(row)
      this.openDialog('org', pageMode.add)
    },
    async handleUpdateOrg(row, index) {
      await this.setOrgTreeData(row)
      this.openDialog('org', pageMode.update, row)
    },
    async setOrgTreeData(row) {
      const result = await getOrgList()
      const orgList = result.data.listLine.map((item) => {
        return { id: item.orgId, name: item.orgName, parentId: item.parentId }
      })
      // 修正的场合，不包含自己
      this.formObj.addForm.orgTreeData = flatArrayToTree(orgList, { exclude: [row?.orgId] })
    },
    handleSaveOrg() {
      this.validateAll(['orgEditDlg'], async() => {
        const _form = { ... this.formObj.addForm.org }
        if (utils.isArray(_form.parentId)) {
          _form.parentId = _form.parentId.length === 0 ? '' : _form.parentId[0]
        }
        if (this.isAddOrg) {
          await createOrg(_form)
        } else {
          await updateOrg(_form)
        }
        this.searchOrgList()
        this.formObj.addForm.showFlg.org = false
      })
    },
    async handleDeleteOrg(row, index) {
      this.$showConfirm({ msg: this.getLang('message.rule.deleteOrgConfirm'), ok: async() => {
        await deleteOrg(row.id)
        setTimeout(async() => {
          this.listObj.org.pagingDefine.page = 1
          this.searchOrgList()
        }, 500)
      } })
    },
    // ----------------------- 组织列表查询 ---------------------
    async searchOrgList() {
      const _target = this.listObj.org
      _target.listLineLoading = true

      const result = await queryOrgList({
        searchForm: this.formObj.searchForm.org,
        likeSearch: this.formObj.searchForm.likeSearch.org,
        pagingDefine: this.listObj.org.pagingDefine
      })

      _target.listLine = result.data.listLine.map((item) => {
        return { treeId: item.orgId, ...item }
      })

      _target.listLine = flatArrayToTree(_target.listLine,
        { schema: { id: 'orgId', name: 'orgName', parentId: 'parentId' }})
      _target.lineNum = result.data.lineNum

      setTimeout(() => {
        _target.listLineLoading = false
      }, 0)
    },
    async searchPersonInCharge(query) {
      if (query !== '') {
        const result = await getPersonInCharge({
          searchForm: { loginName: query, userName: query },
          likeSearch: ['loginName', 'userName']
        })
        this.formObj.addForm.personInChargeData = result.data.listLine.map((item) => {
          return { id: item.loginName, name: `${item.userName}(${item.loginName})` }
        })
      } else {
        this.formObj.addForm.personInChargeData = []
      }
    },

    // ----------------------- Open Dialog ---------------------
    openDialog(target, mode, row, index) {
      const data = row === undefined ? this.$gcom.formObj.addForm[target] : row
      this.formObj.addForm[target] = { ...data }
      this.formObj.addForm.showFlg[target] = true
      this.formObj.addForm.showMode[target] = mode
    },
    // ----------------------- 上级组织有值时必选 ---------------------
    parentIdRequiredValidator(rule, value, callback) {
      if (this.formObj.addForm.orgTreeData.length > 0) {
        if ((utils.isArray(value) && value.length === 0) || utils.isNotContainsVal(value)) {
          callback(new Error(this.getLang('message.rule.parentIdReq')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
  }
}
